package cn.com.project;

import org.apache.rocketmq.common.message.MessageConst;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;

@SpringBootApplication
@EnableBinding({ MySource.class })
@RestController
public class RocketMQProduceApplication {

	public static void main(String[] args) {
		SpringApplication.run(RocketMQProduceApplication.class, args);
	}

	@Autowired
	private MySource mySource;

	@GetMapping("/send")
	public boolean send(String msg) {
		return mySource.output1().send(MessageBuilder.withPayload(msg).build());
	}

	@GetMapping("/sendTag")
	public boolean sendTag() {
		return mySource.output1().send(
				MessageBuilder.withPayload(new Random().nextInt(Integer.MAX_VALUE))
						.setHeader(MessageConst.PROPERTY_TAGS, "tagStr")
						.build());
	}

	@GetMapping("/sendObj")
	public boolean sendObj() {
		return mySource.output1().send(
				MessageBuilder.withPayload(new Foo(new Random().nextInt(Integer.MAX_VALUE)))
						.setHeader(MessageConst.PROPERTY_TAGS, "tagObj")
						.build());
	}

	@GetMapping("/sendTransactional")
	public boolean sendTransactional() {
		// COMMIT_MESSAGE message
		mySource.output2().send(
				MessageBuilder.withPayload("transactional-msg1")
						.setHeader("transactional", 1)
						.build());
		// ROLLBACK_MESSAGE message
		mySource.output2().send(
				MessageBuilder.withPayload("transactional-msg2")
						.setHeader("transactional", 2)
						.build());
		// ROLLBACK_MESSAGE message
		mySource.output2().send(
				MessageBuilder.withPayload("transactional-msg3")
						.setHeader("transactional", 3)
						.build());
		// COMMIT_MESSAGE message
		mySource.output2().send(
				MessageBuilder.withPayload("transactional-msg4")
						.setHeader("transactional", 4)
						.build());
		return true;
	}

}
